package server;

import server.mapper.Mapper;
import server.mapper.MyContext;
import server.mapper.MyHost;
import server.mapper.MyWrapper;

import java.io.InputStream;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class RequestProcessor extends Thread {

    private Socket socket;
//    private Map<String,HttpServlet> servletMap;
    private Mapper mapper;
    public RequestProcessor(Socket socket, Mapper mapper) {
        this.socket = socket;
        this.mapper = mapper;
    }

    @Override
    public void run() {
        try{
            System.out.println("开始执行RequestProcessor----->");
            InputStream inputStream = socket.getInputStream();

            // 封装Request对象和Response对象

            Request request = new Request(inputStream);
            Response response = new Response(socket.getOutputStream());

            String host = request.getHost().split(":")[0];


            String url = request.getUrl();
            String[] urls = url.split("/");

            List<MyHost> myHosts = mapper.getHosts();
            List<MyContext> contexts=new ArrayList<>();
            for (MyHost myHost: myHosts) {
                if (myHost.getName().equals(host)){
                    contexts = myHost.getContexts();
                }
            }
            List<MyWrapper> myWrappers = new ArrayList<>();

            Boolean ifExistContext = false;//是否存在请求容器
            for (MyContext myContext: contexts) {
                if (myContext.getProjectName().equals(urls[1])){
                    myWrappers = myContext.getWrappers();
                    ifExistContext=true;
                }
            }
            if (ifExistContext==false){
                response.outputHtml(url);
            }else{

                String classurl = url.replace("/"+urls[1],"");

                //默认请求动态资源
                Boolean complete = false;//请求完成标识
                for (MyWrapper m :myWrappers) {
                    if (m.getURLPattern().equals(classurl)){
                        HttpServlet httpServlet = m.getServlet();
                        httpServlet.service(request,response);
                        complete=true;
                    }
                }
                if (complete==false){//没有servlet则请求静态资源
                    response.outputHtml(classurl);
                }
            }





            /*// 静态资源处理
            if(servletMap.get(request.getUrl()) == null) {
                response.outputHtml(request.getUrl());
            }else{
                // 动态资源servlet请求
                HttpServlet httpServlet = servletMap.get(request.getUrl());
                httpServlet.service(request,response);
            }*/

            socket.close();

        }catch (Exception e) {
            e.printStackTrace();
        }

    }
}
